// pages/accounts/list/list.js
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
const leadService = require("../../../apiservice/screen/screencustomerservice");

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		accountState: [{
				id: 0,
				name: '未完成'
			},
			{
				id: 1,
				name: '已完成'
			},
			{
				id: 2,
				name: '未预约'
			},
			{
				id: 3,
				name: '已预约'
			},
			{
				id: 4,
				name: '全部'
			},
		],
		accountStateIndex: 4,
		accountStateName: "全部",
		scid: "",
		scstate: 4,
		searchKey: "",
		height: 0,
		screenownerid: '',
		//筛查类型社区、校园
		screentype: '',
		schoolId: '',
		screentemplatetype: '',
    pageSize: 50,
    current: 1,
    totalPages:0
	},

	//筛查小组change时
	accountStateChange: function(e) {

		console.log(e);
		if (this.data.accountState && this.data.accountState.length > 0) {
			var stateName = this.data.accountState[e.detail.value].name;
			var stateCode = this.data.accountState[e.detail.value].id;
			this.setData({
				accountStateIndex: e.detail.value,
				accountStateName: stateName,
				scstate: stateCode,
				current: 1,
				totalPage: 0
			});
			this.GetPage(this.data.scid, stateCode, this.data.searchKey, this.data.current, this.data.pageSize);
		}
	},

	async GetPage(scid, scstate, conditions, pageNum, pageSize) {

		try {
			var result = await leadService.GetScreenCustomerByScreenIdAndSCStaceAndKeyPaging(scid, scstate, conditions,
        pageNum, this.data.pageSize)
			console.log(result);
			if (result.data && result.data && result.data.datas) {
				this.setData({
          ['list[0]']: result.data.datas,
					current: pageNum,
          totalPages: Math.ceil(result.data.total / this.data.pageSize)
				})
			} else {
				this.setData({
          current: 1,
          totalPages:0
				})
			}

		} catch (e) {
			//TODO handle the exception

		} finally {
			wx.hideLoading();
		}
	},

	// lower: async function() {
  //   this.setData({ isUpper: false });
	// 	if (this.data.isnextPage) {
	// 		wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
	// 			title: '加载中',
	// 			icon: 'loading'
	// 		});

	// 		var stateCode = this.data.accountState[this.data.accountStateIndex].id;
	// 		var pageNum = this.data.pagenum;
	// 		var searhKey = this.data.searchKey
  //     await this.GetPage(this.data.scid, stateCode, searhKey, ++pageNum, this.data.pageSize);
	// 	} else {
	// 		wx.showToast({ //如果全部加载完成了也弹一个框
	// 			title: '我也是有底线的',
	// 			icon: 'success',
	// 			duration: 350
	// 		});
	// 		return false;
	// 	}
  //   this.setData({ isUpper: true });
	// },

  // upper: async function () {
  //   if (this.data.isUpper) {
  //     if (this.data.pagenum > 1) {

  //       wx.showLoading({
  //         title: '加载中',
  //         icon: 'loading'
  //       });
  //       var stateCode = this.data.accountState[this.data.accountStateIndex].id;
  //       var pageNum = this.data.pagenum;
  //       var searhKey = this.data.searchKey
  //       await this.GetPage(this.data.scid, stateCode, searhKey, --pageNum, this.data.pageSize);
  //     }
  //     else {
  //       wx.showToast({ //如果全部加载完成了也弹一个框
  //         title: '已经到第1页',
  //         icon: 'success',
  //         duration: 350
  //       });
  //     }
  //   }
  //   this.setData({ isUpper: true });
  // },


	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		var res = wx.getSystemInfoSync();

		this.setData({
			height: res.windowHeight,
			scid: options.scid,
			screenownerid: options.screenownerid,
		});
		if (options.stateCode) {
      this.GetPage(this.data.scid, options.stateCode, this.data.searchKey, this.data.current, this.data.pageSize)
		} else {
      this.GetPage(this.data.scid, 4, this.data.searchKey, this.data.current, this.data.pageSize)
		}

		if (options.screentype) {
			this.setData({
				screentype: options.screentype
			})
		}
		if (options.schoolId) {
			this.setData({
				schoolId: options.schoolId
			})
		}
		if (options.screentemplatetype) {
			this.setData({
				screentemplatetype: options.screentemplatetype
			})
		}
		//console.log("selector:" + options);

	},

	onSearch: async function(e) {
		wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
			title: '加载中',
			icon: 'loading'
		});

		this.setData({
			list: null,
			searchKey: e.detail.searchKey
		})

    await this.GetPage(this.data.scid, this.data.scstate, e.detail.searchKey, this.data.current, this.data.pageSize)

	},
	toModifyPage: function(e) {
		var that = this;
		var scid = that.data.scid;
		var screenownerid = that.data.screenownerid;
		var screentype = that.data.screentype;
		var toUrl = '../../screens/result/modify/modify?scid=' +
			`${scid}&leadid=${e.currentTarget.id}` +
			`&screenownerid=${screenownerid}` +
			`&screentype=${screentype}&screentemplatetype=${this.data.screentemplatetype}`;
		wx.navigateTo({
			url: toUrl,
			events: {
				//回调函数
				ResultModifyEvent: args => {
					that.resultModifyEvent(args, e)
				},
			},
			success: function(res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('acceptDataFromOpenedResultModifyPage', {
					data: e.currentTarget.id
				})
			}
		})
	},

	resultModifyEvent: function(args, e) {
		var that = this;
		var flagbreak = false;
		for (let pageIndex in that.data.list) {
			var dataArray = that.data.list[pageIndex];
			for (let i = 0; i < dataArray.length; i++) {
				if (dataArray[i].new_customerid == e.currentTarget.id) {
					dataArray[i].age = args.data.new_age;
					dataArray[i].customername = args.data.name;
					dataArray[i].sfz = args.data.new_citizenid;
					dataArray[i].iphoneno1 = args.data.address1_telephone1;
					that.setData({
						[`list[${pageIndex}][${i}]`]: dataArray[i]
					});
					flagbreak = true;
					break;
				}
			}
			if (flagbreak) break;
		}
	},


	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},


	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},

	enterDetail: function(e) {
		if (e.currentTarget.dataset.item) {
			console.log('tourl ', e.currentTarget.dataset.item)
			var scid = this.data.scid;
			let toUrl = "../../print/letter/letter?scid=" + scid;
			if (this.data.schoolId) {
				toUrl += `&schoolId=${this.data.schoolId}`
			}
			wx.navigateTo({
				url: toUrl,
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					acceptDataFromOpenedPage: function(data) {
						console.log(data)
					},
					someEvent: function(data) {
						console.log(data)
					}
				},
				success: function(res) {
					// 通过eventChannel向被打开页面传送数据
					res.eventChannel.emit('acceptDataFromOpenerPage', {
						data: e.currentTarget.dataset.item
					})
				}
			})
		}
	},
  onPageChange: async function(e){
    var stateCode = this.data.accountState[this.data.accountStateIndex].id;
    var searhKey = this.data.searchKey
    await this.GetPage(this.data.scid, stateCode, searhKey, e.detail.current, this.data.pageSize);
    this.setData({current:e.detail.current});
  }
})
